import Mock from 'mockjs'
import { param2Obj } from '@/utils'

const List = []
const count = 100
let maxId = 0

for (let i = 0; i < count; i++) {
  const m = Mock.mock({
    id: '@increment',
    sn: '@increment',
    projectId: 1,
    projectName: '项目',
    name: '@first',
    'regSemesterName|1': ['2016上半年', '2016下半年', '2017上半年', '2017下半年', '2018上半年', '2018下半年'],
    regSchool: '@title(5, 10)',
    'regGrade|1': ['1年级', '2年级', '3年级', '4年级', '5年级', '6年级', '7年级', '8年级', '9年级', '高一', '高二', '高三'],
    'gender|1': ['男', '女'],
    'status|1': ['待审核', '已通过', '已删除']
  })
  maxId = m.ID
  List.push(m)
}

export default {
  getList: config => {
    const { page = 1, limit = 20, sort, order } = param2Obj(config.url)

    const mockList = List.filter(item => {
      return true
    })

    if (order === 'asc') {
      mockList.sort((a, b) => {
        if (a[sort] < b[sort]) {
          return -1
        }
        if (a[sort] > b[sort]) {
          return 1
        }
        return 0
      })
    } else if (order === 'desc') {
      mockList.sort((a, b) => {
        if (a[sort] > b[sort]) {
          return -1
        }
        if (a[sort] < b[sort]) {
          return 1
        }
        return 0
      })
    }

    const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1))

    return {
      success: true,
      data: {
        total: mockList.length,
        items: pageList
      }
    }
  },
  getInfo: (config) => {
    const urlArray = config.url.split('/')
    const id = urlArray[urlArray.length - 1]
    for (const item of List) {
      if (item.id === +id) {
        return {
          success: true,
          data: item
        }
      }
    }
  },
  add: (config) => {
    const data = JSON.parse(config.body)
    maxId += 1
    data.id = maxId
    List.push(data)
    return {
      success: true,
      data: data
    }
  },
  update: (config) => {
    const data = JSON.parse(config.body)
    for (const m of List) {
      if (m.id === data.id) {
        const index = List.indexOf(m)
        List.splice(index, 1, data)
        return {
          success: true,
          data: data
        }
      }
    }
  },
  remove: (config) => {
    // console.log(config)
    const urlArray = config.url.split('/')
    const id = urlArray[urlArray.length - 1]
    for (const m of List) {
      if (m.id === +id) {
        const index = List.indexOf(m)
        List.splice(index, 1)
        return {
          success: true
        }
      }
    }
    return {
      success: true
    }
  }
}
